from django.shortcuts import render
from Store.models import *
from Buyer.models import *
from django.http import HttpResponseRedirect

# Create your views here.

import hashlib


def setPassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result


def LoginValid(func):
    def inner(request, *args, **kwargs):
        cookie_userid = request.COOKIES.get("b_userid")
        session_userid = request.session.get("b_userid")
        cookieusername = request.COOKIES.get("b_username")
        if cookie_userid and session_userid:
            flag = QUser.objects.filter(
                id=session_userid,
                username=cookieusername,
                usertype=0
            ).exists()
            if flag:
                return func(request, *args, **kwargs)
        return HttpResponseRedirect("/buyer/bootstrap_login")

    return inner


# 自制base
def base(request):
    return render(request, "buyer/base.html")


# 购物车
@LoginValid
def bootstrap_cart(request):
    # 查询登陆用户的购物车中所有的内容
    userid = request.session.get("b_userid")
    cart_list = Carts.objects.filter(user_id=userid).all()
    return render(request, "buyer/bootstrap_cart.html", locals())


# 用户登录
def bootstrap_login(request):
    if request.method == "POST":
        username = request.POST.get("user_name")
        password = request.POST.get("user_pwd")
        if username and password:
            user = QUser.objects.filter(username=username, password=setPassword(password), usertype=0).first()
            if user:
                resp = HttpResponseRedirect("/buyer/index/")
                resp.set_cookie("b_userid", user.id)
                resp.set_cookie("b_username", user.username)
                request.session["b_userid"] = user.id
                return resp
    return render(request, "buyer/bootstrap_login.html")


# 用户注册
def bootstrap_register(request):
    if request.method == "POST":
        print(request.POST)
        # 先判断用户是否存在
        username = request.POST.get("user_name")
        user = QUser.objects.filter(username=username).first()
        if not user:
            QUser.objects.create(
                username=username,
                password=setPassword(request.POST.get("user_pwd")),
                email=request.POST.get("user_email")
            )
        return HttpResponseRedirect('/buyer/bootstrap_login')
    return render(request, "buyer/bootstrap_register.html")


# 用户退出
def logout(request):
    # 删除
    resp = HttpResponseRedirect("/buyer/index")
    resp.delete_cookie('b_userid')
    resp.delete_cookie("b_username")
    del request.session['b_userid']
    return resp


# 商品详情
def detail(request, id):
    """

    :param request:
    :param id: 商品id
    :return:
    """
    goods = Goods.objects.filter(id=int(id)).first()
    return render(request, "buyer/detail.html", locals())


def edit_address(request):
    return render(request, "buyer/edit-address.html")


def edit_user(request):
    return render(request, "buyer/edit-user.html")


@LoginValid
def addcarts(request):
    """
    接受数据，将数据写入carts表中
    :param request:
    商品id
    数量count
    :return:
    """
    result = {
        "code": "",
        "msg": ""
    }
    goods_id = request.GET.get("goods_id")
    count = request.GET.get("count", 1)
    userid = request.session.get("b_userid")
    if not goods_id:
        result["code"] = "10000"
        result["msg"] = "参数缺少"
        return JsonResponse(result)
    goods = Goods.objects.filter(id=goods_id).first()
    if not goods:
        result["code"] = "10001"
        result["msg"] = "商品不存在"
        return JsonResponse(result)
    # 查询 登陆用户购物车中是否有对应的商品
    cart = Carts.objects.filter(
        goods_id=int(goods_id),
        user_id=userid
    ).first()
    if cart:
        cart.goods_num += int(count)
        cart.total_mount += int(count) * goods.g_price
    else:
        # 添加购物车
        cart = Carts()
        cart.goods_name = goods.g_name
        cart.goods_price = goods.g_price
        cart.goods_num = int(count)
        cart.goods_mount = int(count) * goods.g_price
        cart.goods_picture = goods.g_picutre
        cart.user_id = userid
        cart.goods = goods
    try:
        cart.save()
        result["code"] = "10002"
        result["msg"] = "添加购物车成功"
    except:
        result["code"] = "10003"
        result["msg"] = "请联系管理员"
    return JsonResponse(result)


def updatecart(request):
    # 修改购物车的内容
    status = request.GET.get("status")
    cart_id = request.GET.get("cart_id")
    # print("cart_id:",cart_id)
    # print(type(cart_id))
    cart = Carts.objects.filter(id=int(cart_id)).first()
    if status == "add":
        # +1
        cart.goods_num += 1
        cart.total_mount += cart.goods_price
    elif status == "add":
        # -1
        if cart.goods_num > 1:
            cart.goods_num -= 1
            cart.total_mount -= cart.goods_price
    cart.save()
    return JsonResponse({"code": 10000, "mag": "修改成功"})


@LoginValid
def cartpayorder(request):
    userid = request.session.get("b_userid")
    porder = ""
    if request.method == "POST":
        cart_id_list = request.POST.getlist("cart_id")   # 选中的购物车
        print("cart_id_list:",cart_id_list)
        # 生成订单
        porder = PlaceOrder()
        porder.order_num = str(time.time()).replace(".","")
        porder.type_number = 0  # 选中购物车商品数量的和
        porder.total_price = 0  # 选中的购物车中的小计的和
        porder.user_id_id = userid
        porder.save()

        type_number = 0  # 订单总数量
        total_price = 0  # 订单总金额

        # 生成订单详情
        for cart_id in cart_id_list:
            cart = Carts.objects.filter(id=int(cart_id)).first()
            type_number += cart.goods_num
            total_price += cart.total_mount
            order_info = OrderInfo()
            order_info.goods_name = cart.goods_name
            order_info.goods_price = cart.goods_price
            order_info.goods_num = cart.goods_num
            order_info.goods_picture = cart.goods_picture
            order_info.goods_total = cart.total_mount
            order_info.goods_status = 0
            order_info.store = cart.goods.g_store
            order_info.order = porder
            order_info.save()
            # 删除 cart 内容
            cart.delete()
        porder.total_price = total_price
        porder.type_number = type_number
        porder.save()
        # 获取选中购物车id
    return render(request,"buyer/place_order.html",locals())


def index(request):
    goods_type_list = GoodsType.objects.all()
    data = []
    for g_type in goods_type_list:
        if len(g_type.goods_set.all()) != 0:
            data.append({
                g_type: g_type.goods_set.all()[:5]
            })
    return render(request, "buyer/index.html", locals())


# 我的订单
def myorders(request):
    return render(request, "buyer/myorders.html")


# 商品列表页面
def list(request):
    t_id = request.GET.get("t_id")
    return render(request, 'buyer/list.html', {"t_id": t_id})


import time


# 生成订单
@LoginValid
def place_order(request):
    goods_id = request.GET.get("id")
    print("goods_id:",goods_id)
    count = request.GET.get("count")
    userid = request.session.get("b_userid")
    goods = Goods.objects.filter(id=int(goods_id)).first()
    # 生成 placeorder
    porder = PlaceOrder()
    porder.order_num = str(time.time()).replace(".", "")
    porder.type_number = int(count)
    porder.total_price = goods.g_price * int(count)
    porder.user_id_id = userid
    porder.save()
    # 生成orderinfo
    orderinfo = OrderInfo()
    orderinfo.goods_name = goods.g_name
    orderinfo.goods_price = goods.g_price
    orderinfo.goods_num = count
    orderinfo.goods_picture = goods.g_picutre
    orderinfo.goods_total = goods.g_price * int(count)
    orderinfo.goods_status = 0
    orderinfo.store = goods.g_store
    orderinfo.order = porder
    orderinfo.save()
    return render(request, "buyer/place_order.html", locals())


from django.http import JsonResponse


def redata(request):
    data = {
        "data": []
    }
    type_id = request.GET.get("type_id")
    goods_list = GoodsType.objects.filter(id=type_id).first().goods_set.all()
    print(goods_list)
    for one in goods_list:
        data["data"].append({
            "g_pricutre": str(one.g_picutre),
            "g_name": one.g_name,
            "g_price": one.g_price
        })

    return JsonResponse(data, safe=False)


# # 4、ViewSet类和路由器
# from Buyer.serializer import MoreListSerializer
# from rest_framework import viewsets
# class MorelistView(viewsets.ReadOnlyModelViewSet):
#     def get_queryset(self):
#         # 获取到一个queryset结果
#         # goods_list = Goods.objects.all()[:10]
#         # 返回某个商品的10条数据
#         type_id = self.request.GET.get("type_id")
#         goods_list = GoodsType.objects.filter(id = type_id).first().goods_set.all()
#         return goods_list
#     # 序列化器
#     serializer_class = MoreListSerializer
#
#     # 返回数据 让结果保持原有的样子
#     def get_serializer_context(self):
#         return {
#             "view":self
#         }

def user_center_info(request):
    return render(request, "buyer/user-center-info.html")


# 支付宝支付
from sdk.alipaydemo import alipay


def zfbpay(request):
    # 获取订单id
    order_id = request.GET.get("order_id")
    placeorder = PlaceOrder.objects.filter(id=order_id).first()
    # 实例化订单
    order = alipay.api_alipay_trade_app_pay(
        subject="生鲜交易",  # 交易主题
        out_trade_no=placeorder.order_num,  # 订单号
        total_amount=str(placeorder.total_price),  # 交易金额 字符串类型
        return_url=None,  # 回调
        notify_url=None,  # 通知url
    )

    # 发起支付 构建支付宝支付的url
    res = "https://openapi.alipaydev.com/gateway.do?" + order
    # 返回支付宝的支付地址
    return HttpResponseRedirect(res)


def payresult(request):
    # 获取订单号
    order_num = request.GET.get("out_trade_to")
    # 修改订单状态
    placeorder = PlaceOrder.objects.filter(order_num=order_num).first()
    placeorder.order_status = 1
    placeorder.save()
    return render(request, "buyer/payresult.html", locals())
